package com.itheima.leyou.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itheima.leyou.service.OrderService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class OrderController {

    @Resource
    private OrderService orderService;

    @RequestMapping(value = "/getOrder/{orderid}")
    public Map<String, Object> getOrder(@PathVariable("orderid") String orderid, HttpServletRequest request){
        return orderService.getOrder(orderid);
    }

    @RequestMapping(value = "/createOrder/{jsonObj}")
    @ResponseBody
    public Map<String, Object> createOrder(@PathVariable("jsonObj") String jsonObj, HttpServletRequest request) {
        Map<String, Object> map = JSONObject.parseObject(jsonObj, new TypeReference<Map<String, Object>>() {});
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        Map resultMap = null;
        //map.get("user_id")的验证用于单元测试
        if (userObj == null && map.get("user_id") == null) {
            resultMap = new HashMap();
            resultMap.put("result", false);
            resultMap.put("msg", "会员未登录不能购买！");
            return resultMap;
        }else if(userObj != null){
            Map userMap = (Map) userObj;
            map.put("user_id", userMap.get("id"));
        }
        resultMap = orderService.createOrder(map);
        return resultMap;
    }

    @RequestMapping(value = "updateOrderStatus/{orderid}")
    @ResponseBody
    public Map<String, Object> updateOrderStatus(@PathVariable("orderid") String orderid){
        return orderService.updateOrderStatus(orderid);
    }

    @RequestMapping(value = "payOrder/{orderid}")
    @ResponseBody
    public Map<String, Object> payOrder(@PathVariable("orderid") String orderid){
        return orderService.payOrder(orderid);
    }

    /**
     * 根据sku_id查询订单明细
     * @param sku_id
     * @return
     */
    @RequestMapping(value = "getOrderDetailListBySkuId/{sku_id}")
    @ResponseBody
    public List<Map<String,Object>> getOrderDetailListBySkuId(@PathVariable("sku_id") String sku_id){
        return orderService.getOrderDetailListBySkuId(sku_id);
    }
}
